package com.autohelper.app;


import static com.autohelper.app.PermissionUtils.PERMISSION_REQUEST_CODE;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.autohelper.app.kit.ShortIdGenerator;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int UPDATE_INTERVAL = 1000; // 更新间隔1秒
    public static final int REQUEST_CODE_CAPTURE_SCREEN = 1001;

    private TextView statusText;
    private TextView serviceText;
    private TextView captureText;
    private Button settingsButton;
    private Button startServiceButton;
    private Button stopServiceButton;
    private Button captureButton;

    private MediaProjectionManager mediaProjectionManager;
    private Handler handler;
    private Runnable statusChecker;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(() -> {
            String device_no = ShortIdGenerator.generateShortId(MainActivity.this);
            ServiceHolder.INSTANCE.setDeviceNo(device_no);
            TextView textView = findViewById(R.id.device_id);
            textView.post(() -> textView.setText(device_no));
        }).start();

        mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);

        statusText = findViewById(R.id.status_text);
        settingsButton = findViewById(R.id.settings_button);
        serviceText = findViewById(R.id.service_text);
        startServiceButton = findViewById(R.id.start_service_button);
        stopServiceButton = findViewById(R.id.stop_service_button);
        captureButton = findViewById(R.id.capture_button);
        captureText = findViewById(R.id.capture_text);

        settingsButton.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
            startActivity(intent);
        });

        startServiceButton.setOnClickListener(v -> {
            if (PermissionUtils.isAccessibilityServiceEnabled(this)) {
                String server_ip = ((TextView) findViewById(R.id.server_ip)).getText().toString();
                ServiceHolder.INSTANCE.setServerIp(server_ip);
                Intent serviceIntent = new Intent(this, ForegroundService.class);
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    startForegroundService(serviceIntent);
                } else {
                    startService(serviceIntent);
                }
                updateServiceText();
                startServiceButton.setEnabled(false);
                stopServiceButton.setEnabled(true);
            } else {
                Toast.makeText(this, "请先授权无障碍权限，在启动服务", Toast.LENGTH_LONG).show();
            }
        });

        stopServiceButton.setOnClickListener(v -> {
            Intent serviceIntent = new Intent(this, ForegroundService.class);
            stopService(serviceIntent);
            startServiceButton.setEnabled(true);
            stopServiceButton.setEnabled(false);
        });

        captureButton.setOnClickListener(v -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (!PermissionUtils.isScreenCaptureEnabled(this)) {
                    startActivityForResult(mediaProjectionManager.createScreenCaptureIntent(), REQUEST_CODE_CAPTURE_SCREEN);
                } else {
                    Toast.makeText(this, "截屏权限已授予", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "当前系统版本不支持截屏功能", Toast.LENGTH_SHORT).show();
            }
        });

        // 初始化Handler和状态检查Runnable
        handler = new Handler();
        statusChecker = new Runnable() {
            @Override
            public void run() {
                updateServiceText();
                handler.postDelayed(this, UPDATE_INTERVAL);
            }
        };

        // 检查所有必需权限
        PermissionUtils.checkAndRequestPermissions(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        PermissionUtils.checkAndRequestPermissions(this);
        // 开始定期检查服务状态
        startStatusChecker();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 停止定期检查
        stopStatusChecker();
    }

    private void startStatusChecker() {
        statusChecker.run();
    }

    private void stopStatusChecker() {
        handler.removeCallbacks(statusChecker);
    }

    private void updateServiceText() {
        boolean isAccessibilityEnabled = PermissionUtils.isAccessibilityServiceEnabled(this);
        boolean isForegroundStarted = ForegroundService.isForegroundServiceRunning(this);
        boolean isScreenCaptureEnabled = PermissionUtils.isScreenCaptureEnabled(this);

        runOnUiThread(() -> {
            statusText.setText("无障碍服务状态: " + (isAccessibilityEnabled ? "已启用" : "未启用"));
            settingsButton.setEnabled(!isAccessibilityEnabled);

            serviceText.setText("服务运行状态: " + (isForegroundStarted ? "运行中" : "未启动"));

            captureText.setText("截屏权限状态: " + (isScreenCaptureEnabled ? "已授予" : "未授予"));
            captureButton.setEnabled(!isScreenCaptureEnabled);
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
                Toast.makeText(this, "未授予悬浮窗权限，部分功能可能无法正常使用", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == REQUEST_CODE_CAPTURE_SCREEN) {
            if (resultCode == RESULT_OK) {
                Toast.makeText(this, "截屏权限已授予", Toast.LENGTH_SHORT).show();
                ServiceHolder.INSTANCE.getScreenCaptureManager().setScreenCaptureData(resultCode, data);
            } else {
                Toast.makeText(this, "未授予截屏权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            if (!allGranted) {
                Toast.makeText(this, "部分权限未授予，可能影响功能使用", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        stopStatusChecker();
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}